package com.sx.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sx.bean.Duty;
import com.sx.bean.PtOrgan;
import com.sx.bean.PtRRoleOrgan;
import com.sx.bean.PtUser;
import com.sx.dao.PtOrganDao;
import com.sx.dao.PtRRoleOrganDao;
import com.sx.dao.PtUserDao;
import com.sx.service.PtUserService;
import com.sx.util.Pagination;
import com.sx.util.Utils;

@Service
public class PtUserServiceImpl implements PtUserService{

	@Autowired
	private PtUserDao ptUserDao;
	
	@Autowired
	private PtOrganDao ptOrganDao;
	
	@Autowired
	private PtRRoleOrganDao ptRRoleOrganDao;
	
	//获取所有User
	@Override
	public Pagination<PtUser> getUsers(int pageNumber, int pageSize) {
		int count = ptUserDao.getUsersCount();
		List<PtUser> list = ptUserDao.getUsers((pageNumber-1)*pageSize,pageSize);
		System.out.println(list);
		Pagination<PtUser> lst = new Pagination<PtUser>();
		lst.setPageSize(pageSize);
		lst.setPageNumber(pageNumber);
		lst.setTotal(count);
		lst.setRows(list);
		return lst;
	}

	@Override
	public PtUser getOne(String id) {
		PtUser ptUser =  ptUserDao.getOne(id);
		return ptUser;
	}

	@Override
	public List<PtOrgan> getOrgsByParentId(String parentUUID) {
		List<PtOrgan> ptOrgans = ptOrganDao.getOrgsByParentId(parentUUID);
		return ptOrgans;
	}

	@Override
	public void update(PtUser ptUser,String[] duty) {
		//删除以前的岗位
		ptUserDao.deleteByUserUuid(ptUser.getUserUuid());
		//循环插入现在的岗位
		if (duty!=null) {
			for(String dt : duty) {
				Duty insertDuty = new Duty();
				insertDuty.setUserDutyid(Utils.getUUID());
				insertDuty.setDutyid(dt);
				insertDuty.setUserUuid(ptUser.getUserUuid());
				ptUserDao.insertDuty(insertDuty);
			}
		}
		
		//更新用户信息（其中包括组织的Uuid）
		ptUserDao.updateByPrimaryKeySelective(ptUser);
	}

	@Override
	public List<PtRRoleOrgan> getDutyByOrganId(String organId) {
		List<PtRRoleOrgan> ptRRoleOrgans = ptRRoleOrganDao.getDutyByOrganId(organId);
		return ptRRoleOrgans;
	}
	
	//删除User,即修改status
	@Override
	public void updateStatusOfUser(String userUuid) {	
		System.out.println("1111111111111");
		ptUserDao.updateStatusOfUser(userUuid);
		System.out.println("2222222222222");
	}

	@Override
	public void insert(PtUser ptUser, String[] duty) {
		//插入用户信息
		ptUser.setUserUuid(Utils.getUUID());
		ptUser.setStatus("N");
		ptUserDao.insertSelective(ptUser);
		//新增用户的岗位信息
		if (duty!=null) {
			for(String dt : duty) {
				Duty insertDuty = new Duty();
				insertDuty.setUserDutyid(Utils.getUUID());
				insertDuty.setDutyid(dt);
				insertDuty.setUserUuid(ptUser.getUserUuid());
				ptUserDao.insertDuty(insertDuty);
			}
		}
	}

}
